package com.czy.owner.ui.archive;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.MaintenanceRecordAdapter;
import com.czy.owner.adapter.TestingListAdapter;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.entity.MaintenanceRecord;
import com.czy.owner.entity.TextingListModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.StringUtils;
import com.czy.owner.utils.disk.DiskLruCacheHelper;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.TimeZone;

import butterknife.BindView;

/**
 * Created by King on 2016/7/19 0019.
 * 养车记录
 */
public class MaintenanceRecordActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.rv_maintenance_record)
    EasyRecyclerView rvRecord;
    private CarInfo mCarInfo;
    private MaintenanceRecordAdapter mMaintenanceAdapter = null;
    private long startTime = 0, endTime = 0;
    //    private DiskLruCacheHelper cacheHelper;
    private final String CACHE_KEY = "czy_archive_type";

    private Handler handler = new Handler();
    private int page = 1;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_maintenance_record;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText("养车记录");
        getSubTitle().setText("添加记录");

        if (getIntent().getExtras() == null || (mCarInfo = (CarInfo) getIntent().getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY)) == null) {
            PhoneUtils.ShowToastMessage(MaintenanceRecordActivity.this, "参数异常!");
            finish();
            return;
        }
        initListener();
//        try {
//            cacheHelper = new DiskLruCacheHelper(this);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    @Override
    protected void updateViews() {

    }


    private void initListener() {
        mMaintenanceAdapter = new MaintenanceRecordAdapter(this);
        rvRecord.setLayoutManager(new LinearLayoutManager(this));

        rvRecord.setAdapterWithProgress(mMaintenanceAdapter);

//        rvRecord.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, PhoneUtils.dip2px(this, 1), this.getResources().getColor(R.color.divider_list)));
        View view = LayoutInflater.from(this).inflate(R.layout.view_empty_maintenance, (ViewGroup) this.getWindow().getDecorView(), false);

        rvRecord.setEmptyView(view);
        rvRecord.setErrorView(R.layout.view_error_refresh);
        mMaintenanceAdapter.setMore(R.layout.view_more, this);
        mMaintenanceAdapter.setNoMore(R.layout.view_nomore);
        rvRecord.getErrorView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rvRecord.showProgress();
                onRefresh();
            }
        });
        rvRecord.setRefreshListener(this);
        mMaintenanceAdapter.setOnEditClickListener(new MaintenanceRecordAdapter.OnEditClickListener() {
            @Override
            public void onEdit(MaintenanceRecord m) {
                startActivityForResult(new Intent(MaintenanceRecordActivity.this, ArchiveEditActivity.class).putExtra("maintenance", m).putExtra(Constants.TRANSMISSION_CONTENT_KEY, mCarInfo), 4);

            }

            @Override
            public void onDelete() {
                onRefresh();

            }
        });
        onRefresh();
        getSubTitle().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(MaintenanceRecordActivity.this, ArchiveAddActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, mCarInfo), 4);
            }
        });
    }

    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(MaintenanceRecordActivity.this)) {
                    mMaintenanceAdapter.pauseMore();
                    rvRecord.showError();
                    return;
                }
                page++;
                getMaintenanceData(false);

            }
        }, 1000);
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(MaintenanceRecordActivity.this)) {
                    mMaintenanceAdapter.pauseMore();
                    rvRecord.showError();
                    return;
                }
                page = 1;
                getMaintenanceData(true);
            }
        }, 1000);
    }

    public void setDataList(List<MaintenanceRecord> mMaintenanceData) {
        for (MaintenanceRecord maintenanceRecord : mMaintenanceData) {
            if (maintenanceRecord.getItemList() == null) {
                maintenanceRecord.setItemList(new ArrayList<MaintenanceRecord.DataBeanModel>());
            }
            //自行添加
            if (maintenanceRecord.getCarFilesCostTypeId() != 0) {
                MaintenanceRecord.DataBeanModel dataBeanModel = new MaintenanceRecord.DataBeanModel();
                dataBeanModel.setName(maintenanceRecord.getTypeName());
                dataBeanModel.setNum("1");
                dataBeanModel.setType("carFilesCostTypeId");
                maintenanceRecord.getItemList().add(dataBeanModel);
//                车检单
            } else if ("inspectionOrder".equals(StringUtils.getString(maintenanceRecord.getOrderType(), ""))) {
                maintenanceRecord.getItemList().clear();
                MaintenanceRecord.DataBeanModel dataBeanModel = new MaintenanceRecord.DataBeanModel();
                dataBeanModel.setName("门店车检");
                dataBeanModel.setNum("");
                dataBeanModel.setType("inspectionOrder");
                maintenanceRecord.getItemList().add(dataBeanModel);
            }
        }
        mMaintenanceAdapter.addAll(mMaintenanceData);
    }

    private void getMaintenanceData(final boolean isFrist) {
//        mLoadView.ShowLoadView(getResources().getString(R.string.refresh_loading));
        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CAR_FILES_RECORD);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(MaintenanceRecordActivity.this).getSession());
        params.addBodyParameter("ownerCarId", "" + mCarInfo.getOwnerCarId());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        params.addBodyParameter("page", "" + page);
        params.addBodyParameter("size", "" + 10);
        params.addBodyParameter("serviceStartTime", "" + format.format(startTime));
        params.addBodyParameter("serviceEndTime", "" + format.format(System.currentTimeMillis()));
        MyLog.e("hep", params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("hep", result);
                String strData = PhoneUtils.checkResponseFlag(MaintenanceRecordActivity.this, result);
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");

                if (flag) {
                    String listData = JsonUtil.getJsonValuesString(strData, "list");
                    List<MaintenanceRecord> mMaintenanceData = new Gson().fromJson(listData, new TypeToken<List<MaintenanceRecord>>() {
                    }.getType());
                    if (isFrist) {
                        mMaintenanceAdapter.clear();
                    }
                    if (mMaintenanceData.size() < 10) {
                        mMaintenanceAdapter.stopMore();

                    }
                    setDataList(mMaintenanceData);

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

//                mLoadView.CancleLoadView();
            }
        });


    }

//    private void initRecord() {
//        Collections.sort(mMaintenanceData, new MaintenanceComparator());
//        mMaintenanceAdapter = new MaintenanceRecordAdapter(this);
////        mMaintenanceAdapter.setCustomListener(new MaintenanceRecordAdapter.onCustomClickListener<MaintenanceRecord>() {
////            @Override
////            public boolean onClick(MaintenanceRecord o) {
////                //Toast.makeText(MaintenanceRecordActivity.this, "Come Soon!" + o.toString(), Toast.LENGTH_SHORT).show();
////                return false;
////            }
////        });
//
//        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
//        rvRecord.setLayoutManager(layoutManager);
//        rvRecord.setAdapter(mMaintenanceAdapter);
//
//    }

//    private void checkData() {
//        if (mMaintenanceData == null || mMaintenanceData.size() < 1) {
//            rvRecord.setVisibility(View.GONE);
//            llNone.setVisibility(View.VISIBLE);
//        } else {
//            rvRecord.setVisibility(View.VISIBLE);
//            llNone.setVisibility(View.GONE);
//        }
//    }


    public class MaintenanceComparator implements Comparator<MaintenanceRecord> {

        public int compare(MaintenanceRecord o1, MaintenanceRecord o2) {
            if (o1.getServiceTime() > o2.getServiceTime()) {
                return -1;
            } else {
                return 1;
            }
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 4 && resultCode == RESULT_OK) {
            onRefresh();
        }
    }
}
